package cn.lsh.reducer;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.StringTokenizer;

public class TempReducer extends Reducer<Text, Text, Text, Text> {

	@Override
	protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
		//2020-02 ["10 35","10 45", "03 34"]
		int maxValue = Integer.MIN_VALUE;
		int secondValue = Integer.MIN_VALUE;
		String maxDay = "", secondDay = "";
		for (Text value : values) {
			StringTokenizer st = new StringTokenizer(value.toString()," ");
			String day = st.nextToken();
			int temp = Integer.parseInt(st.nextToken());
			if (temp > maxValue) {
				//当前值大于最大值
				if (!day.equals(maxDay)) {
					//最大值不是同一天
					maxDay = day;
					if (!secondDay.equals(maxDay)) {
						//第二大值和最大值不是同一天
						secondDay = maxDay;
						secondValue = maxValue;
					}
				}
				maxValue = temp;
			} else if (temp > secondValue) {
				//当前值小于等于最大值，大于第二大值
				if (!secondDay.equals(day)) {
					secondDay = day;
				}
				secondValue = temp;
			}
		}
		context.write(new Text(key.toString() + "-" + maxDay), new Text(maxValue + "c"));
		context.write(new Text(key.toString() + "-" + secondDay), new Text(secondValue + "c"));
	}
}
